package com.zsh.wanandroid.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dxq.basic_ui_library.loadSirCallBack.EmptyCallback;
import com.dxq.basic_ui_library.loadSirCallBack.ErrorCallback;
import com.dxq.basic_ui_library.loadSirCallBack.LoadingCallback;
import com.dxq.basic_ui_library.manager.RecyclerViewLinearLayoutManager;
import com.zsh.wanandroid.R;
import com.zsh.wanandroid.api.ApiService;
import com.zsh.wanandroid.base.BaseActivity;
import com.zsh.wanandroid.base.BasePagerFragment;
import com.zsh.wanandroid.bean.ArticleBean;
import com.zsh.wanandroid.bean.ArticleTags;
import com.zsh.wanandroid.bean.BaseResult;
import com.zsh.wanandroid.bean.PageResult;
import com.zsh.wanandroid.http.ApiRequest;
import com.zsh.wanandroid.ui.activity.ArticleActivity;
import com.zsh.wanandroid.ui.adapter.WeChatAdapter;

import java.io.Serializable;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.R.attr.data;

/**
 * @author zsh
 * @date 2020/3/18.
 * 功能：体系文章列表fragment
 */

public class SystemListPagerFragment extends BasePagerFragment {

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private BaseQuickAdapter mAdapter;

    private static int DEFAULT_PAGE;//默认加载第0页

    public static SystemListPagerFragment newInstance(Bundle bundle) {
        SystemListPagerFragment fragment = new SystemListPagerFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (null != arguments) {
            cid = arguments.getInt("cid");
            DEFAULT_PAGE = arguments.getInt("default_page");
        }
    }

    @Override
    protected int onCreateFragmentView() {
        return R.layout.fragment_common;
    }

    @Override
    protected void initView(View view) {
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        //recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setLayoutManager(new RecyclerViewLinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));//添加分割线
        mAdapter = new WeChatAdapter(R.layout.content_item);//公众号
        recyclerView.setAdapter(mAdapter);
        initRefreshEvent();

        //item点击事件
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<ArticleBean<ArticleTags>> data = adapter.getData();
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", (Serializable) data.get(position));
                BaseActivity activity = (BaseActivity) getActivity();
                activity.startActivity(ArticleActivity.class, bundle);
            }
        });
    }

    @Override
    protected void loadNet() {
        load();
    }

    @Override
    protected void onNetReload(View v) {
        mBaseLoadService.showCallback(LoadingCallback.class);
        loadNet();
    }

    private void initRefreshEvent() {
        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = DEFAULT_PAGE;
                isDownRefresh = true;
                loadNet();
            }
        });

        //上拉加载更多
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadNet();
            }
        });

    }

    //获取体系下的数据
    private void load() {
        //这里进行网络请求和数据装载
        ApiService apiService = ApiRequest.getInstance(getContext()).create(ApiService.class);
        apiService.getKnowledgeList(currentPage, cid).
                enqueue(new Callback<BaseResult<PageResult<ArticleBean<ArticleTags>>>>() {
                    @Override
                    public void onResponse(Call<BaseResult<PageResult<ArticleBean<ArticleTags>>>> call,
                                           Response<BaseResult<PageResult<ArticleBean<ArticleTags>>>> response) {
                        BaseResult<PageResult<ArticleBean<ArticleTags>>> body = response.body();
                        swipeRefreshLayout.setRefreshing(false);
                        if (body == null) {
                            mBaseLoadService.showCallback(EmptyCallback.class);
                            return;
                        }
                        PageResult<ArticleBean<ArticleTags>> data = body.getData();
                        currentPage = data.getCurPage();//当前页
                        pageCount = data.getPageCount();//总页数
                        if (null == data) {
                            mBaseLoadService.showCallback(EmptyCallback.class);
                            return;
                        }
                        List<ArticleBean<ArticleTags>> datas = data.getDatas();
                        if (null != datas && datas.size() > 0) {
                            mBaseLoadService.showSuccess();
                            //下拉刷新
                            if (isDownRefresh) {
                                mAdapter.replaceData(datas);
                            } else {
                                mAdapter.addData(datas);
                            }
                            isDownRefresh = false;
                            if (currentPage < pageCount) {
                                mAdapter.loadMoreComplete();//加载完成（注意不是加载结束，而是本次数据加载结束并且还有下页数据）
                            } else {
                                mAdapter.loadMoreEnd();//加载结束
                            }
                        } else {
                            mBaseLoadService.showCallback(EmptyCallback.class);
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseResult<PageResult<ArticleBean<ArticleTags>>>> call, Throwable t) {
                        swipeRefreshLayout.setRefreshing(false);
                        mBaseLoadService.showCallback(ErrorCallback.class);
                        currentPage = DEFAULT_PAGE;
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mIsFirstLoad = true;
        mIsPrepare = false;
        mIsVisible = false;
        if (rootView != null) {
            //((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

}
